package 注解;

import java.lang.reflect.Field;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;

//使用@Range注解来检查Java Bean的字段。如果字段类型是String，就检查String的长度，如果字段是int，就检查int的范围。
public class 使用字段注解 {
    public static void main(String[] args) throws Exception {
        Person p1 = new Person("Bob", "Beijing", 1);
        Person p2 = new Person("", "Shanghai", 1);
        Person p3 = new Person("Alice", "Shanghai", 1);
        for (Person p : new Person[]{p1, p2, p3}) {
            try {
                check(p);
                System.out.println("Person " + p + " checked ok.");
            } catch (IllegalArgumentException e) {
                System.out.println("Person " + p + " checked failed: " + e);
            }
            System.out.println("______________________________________");
        }
    }
    //分别检查字符符型字段值的长度，Integer型字段值是否符合注解要求
    static void check(Person person) throws IllegalArgumentException, ReflectiveOperationException {
    	Field[] files=person.getClass().getFields();
        for (Field field : files) {
            Range range = field.getAnnotation(Range.class);//字段注解仅1个
            //Annotation[] range1 = field.getDeclaredAnnotations();//如果字段注解个数大于1
            //System.out.println(range1.length);
            if (range != null) {
                Object value = field.get(person);//Object:无法确定字段类型， 字段的值
                // 如果值是String:
                if (value instanceof String) {
                    String s = (String) value;
                    // 判断值是否满足@Range的min/max:
                    if (s.length() < range.min() || s.length() > range.max()) {
                        throw new IllegalArgumentException("Invalid field: " + field.getName());
                    } else {
                        System.out.println(field.getName() + ":  success!!!");
                    }
                }
                // Integer:
                if (value instanceof Integer) {
                    //Integer s = (Integer) value;
                    int s=Integer.valueOf((String) value);
                    // 判断值是否满足@Range的min/max:
                    if (s < range.min() || s > range.max()) {
                        throw new IllegalArgumentException("Invalid field: " + field.getName());
                    } else {
                        System.out.println(field.getName() + ":  success!!!");
                    }
                }
            }
        }
    }
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Range {
    int min() default 0;
    int max() default 255;
}
class Person {
    @Range(min=1, max=20)
    public String name;

    @Range(max=10)
    public String city;
    
    public Integer x;

    public Person(String name,String city,Integer x) {
    	this.name=name;
    	this.city=city;
    	this.x=x;
    	
    }
}